<?php


namespace app\base\service;

use app\base\model\RedianData;
use app\base\model\RedianTask;
use Predis\Command\Redis\DUMP;
use think\admin\service\AdminService;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Cache;
use think\Exception;

/**
 * 任务服务
 * Class AdminService
 * @package think\admin\service
 */
class TaskService extends AdminService
{

    //开始采集任务(直采)
    public function startGather($task,$task_run_log_id=0,$hashid="")
    {
        $num = $task['num'];
        $pages = ceil($num/50);
        $list = [];
        $user_id = $task['user_id'];
        $keywords = $task['keywords'];
//        // 将多行文本按换行符分割成数组
//        $remarkLines = explode("\n",$task['keywords']);
//        // 去除每一行的前后空格
//        $remarkLines = array_map('trim', $remarkLines);
//        // 去除空行
//        $remarkLines = array_filter($remarkLines, function($line) {
//            return !empty($line);
//        });
//        $keywords = "";
//        foreach ($remarkLines as $k=>$v){
//            $keywords.=$v.",";
//        }
      //  $this->app->log->error("热点采集关键字:",$keywords);
        $list =  RedianData::mQuery()->where(['task_id'=>$task['id'],'task_run_log_id'=>$task_run_log_id])->select()->toArray();
        if(empty($list)){
            for($i=1;$i<=$pages;$i++){
                $res = TophubdataService::instance()->search($user_id,$keywords,$i,$hashid);
                if($res['code']==0){
                    $this->insetLog(2,$task['id'],"热点采集失败:".$res['msg']);
                    return 0;
                }else{
                    // $res = $res['data'];
                    $r= MemberService::instance()->charge($user_id,"ByRdGather",$task);
                    if($r['code']==0){
                        $this->insetLog(2,$task['id'],"热点采集失败:".$r['msg']);
                        return -1;
                    }
                    $list = array_merge($list,$res['data']['items']);
                }
            }
            $save_title = [];
            foreach ($list as $k=>$v){
                if(RedianData::mk()->where(['task_id'=>$task['id'],'filter_status'=>1])->whereLike('title',"%".$v['title']."%")->count()==0){
                    if(!in_array($v['title'],$save_title)){
                        $data = [
                            'task_id'=>$task['id'],
                            'title'=>$v['title'],
                            'url'=>$v['url'],
                            'description'=>$v['description'],
                            'thumbnail'=>$v['thumbnail'],
                            'extra'=>$v['extra'],
                            'time'=>$v['time'],
                            'content'=>$v['description'],
                            'task_run_log_id'=>$task_run_log_id,
                            'push_time'=>"1970-01-01 00:00:00",
                            'is_auto_fb'=>$task['is_auto_fb'],
                            'is_auto_jjjb'=>$task['is_auto_jjjb'],
                            'is_auto_fbjb'=> $task['is_auto_fbjb'],
                        ];
                        RedianData::mk()->insert($data);
                        $save_title[] = $v['title'];
                    }

                }
                $this->insetLog(1,$task['id'],"采集到热点数据:".$v['title'],$task_run_log_id);


            }
            if(empty($list)){
                $this->insetLog(2,$task['id'],"热点采集失败,未查询到数据请更换搜索关键词");
            }else{
                $this->insetLog(1,$task['id'],"热点采集成功");
            }
        }


        return $list;

    }

    //开始采集任务(coze_榜眼)
    public function startGatherCoze($task,$pages=1)
    {
        //$num = $task['num'];
       // $pages = ceil($num/50);
        $data = [
            'keyword'=>$task['keywords'],
            'pages'=>$pages,
            'apiKey'=>"329f89155d44331afeaf39039581fe9e"
        ];
        $res = CozeService::instance()->runWorkflow("7497146645411282996",$data);
        return $res;

    }
    //开始采集任务(coze_榜眼_节点)
    public function startGatherCozeNode($task,$pages=1,$node_id=0)
    {
        //$num = $task['num'];
        // $pages = ceil($num/50);
        $data = [
            'keyword'=>$task['keywords'],
            'pages'=>$pages,
            'apiKey'=>"329f89155d44331afeaf39039581fe9e",
            "hashid"=>$node_id
        ];
        $res = CozeService::instance()->runWorkflow("7511747390979571749",$data);
        return $res;

    }

    //查询coze运行结果(榜眼数据采集)
    public function getWorkflowResult($task,$execute_id,$task_run_log_id=0,$workflow_id="7497146645411282996")
    {
       // $this->app->log->info("查询coze运行结果,任务ID".$execute_id);
        $res = CozeService::instance()->getWorkflowResult($execute_id,$workflow_id);
        if($res['code']==0){
//            RedianTask::mQuery()->where(["id"=>$task['id']])->update(['progress'=>7,'error_msg'=>"采集失败"]);
//            if($task_run_log_id){
//                $this->app->db->name("task_run_log")->where(["id"=>$task_run_log_id])->update(['result'=>"采集失败"]);
//            }
            $this->app->log->info("查询coze运行结果榜眼数据采集错误".json_encode($res));
            return 0;
        }else{
           // $this->app->log->info("查询coze运行结果".json_encode($res));
            $data = $res['data'][0];
            if($data['execute_status']=="Success"){
                $output = json_decode($res['data'][0]['output'],true);

                $task_datas =  json_decode($output['Output'],true);
                //$this->app->log->info("查询coze运行结果",$task_datas);
                $ys_num=0;
                if($task_datas['output']){
                    $save_title = [];
                    foreach ($task_datas['output'] as $k=>$t){
                        if(RedianData::mk()->where(['task_id'=>$task['id'],'filter_status'=>1])->whereLike('title',"%".$t['title']."%")->count()==0){
                            if(!in_array($t['title'],$save_title)){
                                $content = $t['description'];
                                if($t['content']){
                                    $c = $this->extractContent($t['content']);
                                    if($c){
                                        $content = $c;
                                    }
                                }
                                $save_data = [
                                    'user_id'=>$task['user_id'],
                                    'description'=>$t['description'],
                                    'content'=>$content,
                                    'url'=>$t['url'],
                                    'title'=>$t['title'],
                                    'task_id'=>$task['id'],
                                    'task_run_log_id'=>$task_run_log_id,
                                    'push_time'=>"1970-01-01 00:00:00",
                                    'is_auto_fb'=>$task['is_auto_fb'],
                                    'is_auto_jjjb'=>$task['is_auto_jjjb'],
                                    'is_auto_fbjb'=> $task['is_auto_fbjb'],
                                ];
                                $this->insetLog(1,$task['id'],"采集到热点数据:".$t['title'],$task_run_log_id);
                                RedianData::mk()->insert($save_data);
                                $save_title[] = $t['title'];
                            }

                            $ys_num++;
                        }

//                        if($t['code']==null && $t['data']){
//                            if(RedianData::mk()->where(['task_id'=>$task['id'],'filter_status'=>1])->whereLike('title',"%".$t['data']['title']."%")->count()==0){
//                                $save_data = [
//                                    'user_id'=>$task['user_id'],
//                                    'content'=>$t['data']['content'],
//                                    'title'=>$t['data']['title'],
//                                    'task_id'=>$task['id'],
//                                    'task_run_log_id'=>$task_run_log_id,
//                                    'push_time'=>"1970-01-01 00:00:00"
//                                ];
//                                RedianData::mk()->insert($save_data);
//                                $ys_num++;
//                            }
//                        }

                    }
                    return 1;
                }else{
                    return 3;
                }


            }else{
                return 2;
            }

        }
    }

    //相似度计算
    public function similarity($task,$task_run_log_id=0)
    {
        $user_id = $task['user_id'];
        $redian_data = RedianData::mQuery()->where(['task_id'=>$task['id'],'task_run_log_id'=>$task_run_log_id])->whereNull("similarity")->select()->toArray();
        foreach ($redian_data as &$v){
            $content = $v['title'];
            if($v['content']){
                //清除html代码
                $content.=strip_tags(htmlspecialchars_decode($v['content']));
            }

            $res = AlibailianService::instance()->similarity($user_id,$task['keywords'],$content);
            if($res['code']==1){
                $similarity_str = $res['data'];
                //提取$similarity中的第一个一位或两位数字
                preg_match('/\d+/', $similarity_str, $matches);
                $similarity=  $matches ? substr($matches[0], 0, 2) : '';
                $v['similarity'] = $similarity;
                $this->insetLog(1,$task['id'],"DTW 文案匹配度{$similarity}%",$task_run_log_id);
            }else{
                $v['similarity'] = 0;
                $this->insetLog(2,$task['id'],"热点{$v['title']}大模型识别相似度失败!");

            }

//            if($task['text_select_type']==2){
//
//
//            }else{
//                $v['similarity'] = SimilarityService::instance()->similarity($task['keywords'],$content);
//                $this->insetLog(1,$task['id'],"热点【{$v['title']}】本地识别相似度成功!");
//            }

            RedianData::mk()->where(['id'=>$v['id']])->save($v);
        }
        return RedianData::mQuery()->where(['task_id'=>$task['id'],'task_run_log_id'=>$task_run_log_id])->where('similarity','>',0)->count();
    }




    //口播文本生成
        public function textGenerate($task,$task_run_log_id=0)
    {
        $user_id = $task['user_id'];
        $redian_data = RedianData::mQuery()->where(['task_id'=>$task['id'],'filter_status'=>1,'task_run_log_id'=>$task_run_log_id])
            ->whereIn("gaixie_status","1,3")->select()->toArray();
        foreach ($redian_data as &$v){
            $user_content = str_replace( ['{{标题}}', '{{描述}}'], [$v['title'], $v['content']], $task['user_prompt']);
            $system_content = str_replace( ['{{标题}}', '{{描述}}'], [$v['title'], $v['content']], $task['system_prompt']);
            $this->insetLog(1,$task['id'],"Seq2Seq 文案语义优化中 ",$task_run_log_id);
           // $res = HuoshanService::instance()->createText($user_id,$system_content,$user_content);
            $res = AlibailianService::instance()->createText($user_id,$system_content,$user_content);

            $beans = MemberService::instance()->getUserRemainingBeans($task['user_id']);
            if($beans < 2){
                $v['ai_gaixie_content'] = '改写失败:蓝豆不足';
                $v['gaixie_status'] = 3;
                $this->insetLog(2,$task['id'],"热点{$v['title']}改写失败：蓝豆不足",$task_run_log_id);
            }else{
                if($res['code']){
                    // 使用正则表达式提取视频标题
                    if (preg_match('/文本标题:(.*?)文本话题:/s', $res['data'], $matches)) {
                        $v['video_title'] = trim($matches[1]); // 提取并去除多余空格
                    }
                    // 使用正则表达式提取文本话题
                    if (preg_match('/文本话题:(.*?)文本描述:/s', $res['data'], $matches)) {
                        $v['video_keywords'] = trim($matches[1]); // 提取并去除多余空格
                    }
                    // 使用正则表达式提取文本描述
                    if (preg_match('/文本描述:(.*?)口播文本开始:/s', $res['data'], $matches)) {
                        $v['video_content'] = trim($matches[1]); // 提取并去除多余空格
                    }


                    // 使用正则表达式提取口播文本
                    if (preg_match('/口播文本开始:(.*?)播报情绪开始:/s', $res['data'], $matches)) {
                        $broadcastText = trim($matches[1]); // 提取并去除多余空格
                        if($broadcastText){
                            $gaixie_status = 2;
                        }else{
                            $broadcastText="未识别到文案";
                            $gaixie_status = 3;
                        }

                    }elseif(preg_match('/口播文本开始:(.*?)/s', $res['data'], $matches)) {
                        $broadcastText = trim($matches[1]); // 提取并去除多余空格
                        if($broadcastText){
                            $gaixie_status = 2;
                        }else{
                            $broadcastText="未识别到文案";
                            $gaixie_status = 3;
                        }
                    } else {
                        $broadcastText = $res['data'];
                        $gaixie_status = 3;
                    }
                    $this->insetLog(1,$task['id'],"Transformer 多模态文案情绪特征分析中 ",$task_run_log_id);

                    // 使用正则表达式提取播报情绪
                    if (preg_match('/播报情绪开始:(.*)/', $res['data'], $matches)) {
                        $broadcastEmotion = trim($matches[1]); // 提取并去除多余空格
                        $this->insetLog(1,$task['id'],"3D CNN 文案情绪特征识别完成！",$task_run_log_id);
                    } else {
                        $broadcastEmotion = "";
                    }
                    $video_keywords = $v['video_keywords'].$task['zdy_video_keywords'];
                    $video_keywords_arr = explode('#',$video_keywords);
                    if($c =count($video_keywords_arr)>5){
                        $video_keywords = array_slice($video_keywords_arr,$c-6,5);
                        $video_keywords = implode('#',$video_keywords);
                        $video_keywords = "#".$video_keywords;
                    }
                    $v['ai_gaixie_content'] = $broadcastText;
                    //加入计费逻辑
                    if($gaixie_status==2){
                        $charge_r = MemberService::instance()->charge($user_id,"textGenerate",$v,"阿里百炼");
                        if($charge_r['code']==0){
                            $broadcastEmotion = $video_keywords = null;
                            $broadcastText = '改写失败:'.$charge_r['msg'];
                            $gaixie_status = 3;
                            $this->insetLog(1,$task['id'],"热点【{$v['title']}】改写失败:".$charge_r['msg'],$task_run_log_id);
                        }

                    }
                    $v['video_keywords'] = $video_keywords;
                    $v['ai_gaixie_content'] = $broadcastText;
                    $v['emotion'] = $broadcastEmotion;
                    $v['gaixie_status'] = $gaixie_status;

                }else{
                    $v['ai_gaixie_content'] = '改写失败:'.$res['msg'];
                    $v['gaixie_status'] = 3;
                    $this->insetLog(2,$task['id'],"热点【{$v['title']}】改写失败：".$res['msg']);
                }
            }



            RedianData::mk()->where(['id'=>$v['id']])->save($v);
        }
        return   RedianData::mQuery()->where(['task_id'=>$task['id'],'gaixie_status'=>2,'task_run_log_id'=>$task_run_log_id])->count();

    }

    //音频生成
    public function audioGenerate($task,$task_run_log_id=0)
    {
        $user_id = $task['user_id'];
        $redian_data = RedianData::mQuery()->where(['task_id'=>$task['id'],'gaixie_status'=>2,'task_run_log_id'=>$task_run_log_id])->select()->toArray();
        foreach ($redian_data as &$v){
            $beans = MemberService::instance()->getUserRemainingBeans($task['user_id']);
            if($beans < 2){
                $v['ai_audio_content'] = '音频生成失败:蓝豆不足';
                $v['audio_status'] = 3;
                $this->insetLog(2,$task['id'],"热点【{$v['title']}】音频生成失败：蓝豆不足");
            }else{
                $this->insetLog(1,$task['id'],"CLIP 音频模板匹配中 ",$task_run_log_id);
                if(empty($task['voice'])){
                    $voices = $this->app->db->name("ai_voice")->where(['type'=>1,'user_id'=>$user_id,"platform_name"=>$task['audio_platform']])->column("code");
                    if(empty($voices)){
                        $voice = null;
                    }else{
                        if($v['emotion']){
                            $voice = $this->app->db->name("ai_voice")->where(['emotion'=>$v['emotion'],'type'=>1,'user_id'=>$user_id,"platform_name"=>$task['audio_platform']])->value("code");
                            if(empty($voice)){
                                $voice = $voices[array_rand($voices)];
                            }
                        }else{
                           // $voices = $this->app->db->name("ai_voice")->where(['type'=>1,'user_id'=>$user_id,"platform_name"=>$task['audio_platform']])->column("code");
                            $voice = $voices[array_rand($voices)];
                        }
                      //  $voice = $voices[array_rand($voices)];
                    }


                }else{
                    $voice =  $this->app->db->name("ai_voice")
                        ->where(['type'=>1,'user_id'=>$user_id,"platform_name"=>$task['audio_platform'],"id"=>$task['voice']])->value("code");
                }
                if(empty($voice)){
                    $v['audio_errmsg'] = "音频模板未找到";
                    $v['audio_status'] = 4;
                    $this->insetLog(2, $task['id'], "热点【{$v['title']}】音频生成失败!失败原因:模板未找到");
                }else{
                    $this->insetLog(1,$task['id'],"Tacotron2 音频情感调校中 ",$task_run_log_id);
                    switch ($task['audio_platform']){
                        case "MINIMAX":
                            $res = MinimaxService::instance()->createVoiceFile($user_id,$v['ai_gaixie_content'],$voice,$task['voice_model'],$v['emotion'],$v['id']);
                            break;
                        case "蝉镜":
                            $res = ChanjingService::instance()->createAudio($user_id,$voice,$v['ai_gaixie_content']);
                            break;
                        default:
                            $res = ['cdoe'=>0,'msg'=>"平台暂不支持"];
                    }

                    if($res['code']){
                        switch ($task['audio_platform']){
                            case "MINIMAX":
                                $v['audio_url'] = $res['data'];
                                $v['audio_status'] = 3;
                                break;
                            case "蝉镜":
                                $v['audio_id'] = $res['data'];
                                $v['audio_status'] = 2;
                                break;
                        }

                        $v['audio_errmsg'] = null;
                        $this->insetLog(1,$task['id'],"WaveNet 音频合成中 ",$task_run_log_id);
                    }else {
                        $v['audio_errmsg'] = $res['msg'];
                        $v['audio_status'] = 4;
                        $this->insetLog(2, $task['id'], "热点【{$v['title']}】音频生成失败!");
                    }
                }
            }




            RedianData::mk()->where(['id'=>$v['id']])->save($v);
        }
        if($task['audio_platform']=="MINIMAX"){
            return RedianData::mQuery()->where(['task_id'=>$task['id'],'audio_status'=>3,'task_run_log_id'=>$task_run_log_id])->count();
        }else{
            return RedianData::mQuery()->where(['task_id'=>$task['id'],'task_run_log_id'=>$task_run_log_id])->whereIn('audio_status',[2,3])->count();
        }


    }


    //查询音频状态
    public function audioStatus($task,$user_id)
    {
        $redian_data = RedianData::mQuery()->where(['task_id'=>$task['id']])->whereNotNull('audio_id')->select()->toArray();
        foreach ($redian_data as &$v){
            if(!empty($v['audio_id'])){
                $res = HuoshanService::instance()->getAudioStatus($user_id,$v['audio_id']);
                if(isset($res['audio_url'])){
                    $v['audio_url'] = $res['audio_url'];
                    $v['audio_status'] = 3;
                    $v['audio_errmsg'] = null;
                    RedianData::mk()->where(['id'=>$v['id']])->save($v);
                }
            }
        }
        return $redian_data;
    }

    //视频生成
    public function videoGenerate($task,$task_run_log_id=0)
    {
        $user_id = $task['user_id'];
        $redian_data = RedianData::mQuery()->where(['audio_status'=>3,'task_id'=>$task['id'],'task_run_log_id'=>$task_run_log_id])->select()->toArray();
       // $this->app->log->error("视频生成任务开始");
       // $this->app->log->error(json_encode($redian_data));
        foreach ($redian_data as &$v){

            $beans = MemberService::instance()->getUserRemainingBeans($task['user_id']);
            if($beans < 2){
                $v['video_errmsg'] = "视频生成失败:蓝豆不足";
                $v['video_status'] = 3;
                $this->insetLog(2,$task['id'],"热点【{$v['title']}】视频生成失败：蓝豆不足");
            }else{
                $this->insetLog(1,$task['id'],"LSTM 视频模板匹配中 ",$task_run_log_id);
                if(empty($task['video'])){
                    $voices = $this->app->db->name("ai_voice")->where(['type'=>2,'user_id'=>$user_id,"platform_name"=>$task['video_platform']])->column("code");
                    if(empty($voices)){
                        $video = null;
                    }else{
                        if($v['emotion']){
                            $video = $this->app->db->name("ai_voice")->where(['emotion'=>$v['emotion'],'type'=>2,'user_id'=>$user_id,"platform_name"=>$task['video_platform']])->value("code");
                            if(empty($voice)){
                                $video = $voices[array_rand($voices)];
                            }
                        }else{
                            // $voices = $this->app->db->name("ai_voice")->where(['type'=>1,'user_id'=>$user_id,"platform_name"=>$task['audio_platform']])->column("code");
                            $video = $voices[array_rand($voices)];
                        }
                    }

                }else{
                    $video = $this->app->db->name("ai_voice")->where(['id'=>$task['video'],'type'=>2,'user_id'=>$user_id,"platform_name"=>$task['video_platform']])->value("code");
                }
                if(empty($video)){
                    $v['video_errmsg'] = "视频模板未找到";
                    $v['video_status'] = 4;
                    $this->insetLog(2,$task['id'],"热点【{$v['title']}】视频生成任务创建失败!失败原因:视频模板未找到");
                }else{
                    $this->insetLog(1,$task['id'],"GAN 3D 视频渲染中 ",$task_run_log_id);
                    switch ($task['video_platform']){
                        case "HeyGen":
                            $res = HeygenService::instance()->createVideo($user_id,$v['audio_url'],$video);
                            break;
                        case "蝉镜":
                            $res = ChanjingService::instance()->createAvatarVideo($user_id,$video,$v['audio_url']);
                            break;
                        case "小甲鱼":
                            $res = XjyService::instance()->createAvatarVideo($video,$v['audio_url']);
                            break;
                        default:
                            $res = ['code'=>0,'msg'=>"平台暂不支持"];
                    }

                    if($res['code']){
                        $v['video_id'] = $res['data'];
                        $v['video_status'] = 2;
                        $v['video_errmsg'] = null;
                        $v['video_url'] = null;
                        $v['video_url_caption'] = null;
                        $v['video_data'] = null;
                        $this->insetLog(1,$task['id'],"BERT 语义引擎解析文案中",$task_run_log_id);
                    }else{
                        $v['video_errmsg'] = $res['msg'];
                        $v['video_status'] = 4;
                        $this->insetLog(2,$task['id'],"热点【{$v['title']}】视频生成任务创建失败!失败原因:".$res['msg'],$task_run_log_id);
                    }
                }
            }





            RedianData::mk()->where(['id'=>$v['id']])->save($v);

        }
        return  RedianData::mQuery()->where(['video_status'=>2,'task_id'=>$task['id'],'task_run_log_id'=>$task_run_log_id])->count();
    }

    //查询视频状态
    public function videoStatus($task,$task_run_log_id=0)
    {
        $user_id = $task['user_id'];
        $redian_data = RedianData::mQuery()->where(['video_status'=>2,'task_id'=>$task['id'],'task_run_log_id'=>$task_run_log_id])->whereNotNull("video_id")->select()->toArray();
        foreach ($redian_data as &$v){
            $res = HeygenService::instance()->getVideoStatus($user_id,$v['video_id']);
            if($res['code']){
                if($res['data']['status']=="completed" && !empty($res['data']['video_url'])){
                    //下载视频到本地服务器
                    $date = date('Ymd');
                    $savePath = app()->getRootPath() . 'public/videos/' . $date . '/';
                    if (!is_dir($savePath)) mkdir($savePath, 0755, true);

                    // 下载主视频
                    $videoContent = file_get_contents($res['data']['video_url']);
                    $videoName = 'video_' . $v['id'] . '_' . time() . '.mp4';
                    file_put_contents($savePath . $videoName, $videoContent);
                    $video_url = "http://dev.blueant.pro/videos/$date/$videoName";



                    $v['video_url'] = $video_url;
                    $v['video_status'] = 3;
                    $v['video_errmsg'] = null;
                    $v['video_url_caption'] = $res['data']['video_url_caption'];
                    $v['video_data'] = json_encode($res['data']);
                    $this->insetLog(1,$task['id'],"NeRF 3D 视频生成完成！",$task_run_log_id);
                }elseif($res['data']['status']=="failed"){
                    $v['video_errmsg'] = "视频生成失败!失败原因".$res['data']['error']['detail'];
                    $v['video_status'] = 4;
                    $this->insetLog(2,$task['id'],"热点【{$v['title']}】视频生成失败!失败原因:".$res['data']['error']['detail'],$task_run_log_id);
                }
                RedianData::mk()->where(['id'=>$v['id']])->save($v);
            }else{
                $this->insetLog(2,$task['id'],"热点【{$v['title']}】视频状态查询失败!错误原因:".$res['msg'],$task_run_log_id);

            }

        }
        return $redian_data;
    }

    //查询视频状态(小甲鱼)
    public function videoStatusXiaojiayu($task,$task_run_log_id=0)
    {
        $user_id = $task['user_id'];
        $redian_data = RedianData::mQuery()->where(['video_status'=>2,'task_id'=>$task['id'],'task_run_log_id'=>$task_run_log_id])->whereNotNull("video_id")->select()->toArray();
        foreach ($redian_data as &$v){
            $this->insetLog(1,$task['id'],"CNN 视频生成进度查询中",$task_run_log_id);
            $res = XjyService::instance()->getAvatarVideoInfo($v['video_id']);
            if($res['code']==1){
                if($res['data']['state']==20){
                    $v['video_url'] = $res['data']['videoUrl'];
                    $v['video_status'] = 3;
                    $v['video_errmsg'] = null;
                    $v['video_data'] = json_encode($res['data']);
                    $v['video_duration'] = $res['data']['duration'];
                    //加入计费逻辑
                    $charge_r = MemberService::instance()->charge($v['user_id'],"videoGenerate",$v,"小甲鱼");
                    if($charge_r['code']==0){
                        $this->app->db->name("redian_data")->where(['video_id'=>$v['video_id']])->update([
                            'video_status'=>4,
                            'video_errmsg'=>"生成失败:".$charge_r['msg'],
                            'video_data'=>json_encode($res['data'])
                        ]);
                    }
                    $this->insetLog(1,$task['id'],"视频生成成功!",$task_run_log_id);
                }elseif($res['data']['state']==30){
                    $v['video_errmsg'] = "视频生成失败!失败原因".$res['data']['tips'];
                    $v['video_status'] = 4;
                }

            }
            RedianData::mk()->where(['id'=>$v['id']])->save($v);
        }
        return $redian_data;
    }



    //查询Heygen上的视频模板列表
    public function getVideoTemplateList($user_id)
    {
        $list = HeygenService::instance()->getVideoTemplate($user_id);
        return $list;
    }


    //插入任务日志
    public function insetLog($type,$task_id,$msg='',$task_run_log_id=0)
    {
        $this->app->db->name("task_log")->insert([
            'type'=>$type,
            'task_id'=>$task_id,
            'task_run_log_id'=>$task_run_log_id,
            'content'=>$msg
        ]);
    }

    //解析自定义口播文本
    public function parseExcel($file_url)
    {
        $parsedUrl = parse_url($file_url);
        $file_path = $this->app->getRootPath() . "public" . $parsedUrl['path'];
        $data = [];

        try {
            // 启用流式读取模式
            $reader = IOFactory::createReader('Xlsx');
            $reader->setReadDataOnly(true); // 只读数据不处理格式
            $reader->setReadEmptyCells(false); // 忽略空单元格
            $spreadsheet = $reader->load($file_path);

            $worksheet = $spreadsheet->getActiveSheet();
            $data = [];
            $rowCount = 0;

            // 逐行处理数据
            foreach ($worksheet->getRowIterator() as $row) {
                // 限制最大处理行数
                //if (++$rowCount > 101) break;

                $cellIterator = $row->getCellIterator();
              //  $cellIterator->setIterateOnlyExistingCells(true); // 只遍历有数据的单元格

                $rowData = [];
                foreach ($cellIterator as $cell) {
                    $rowData[] = $cell->getValue();
                }

                // 即时处理数据
                if (!empty($rowData[3])) {
                    if ($rowCount === 1) {
                        // 验证标题行
                        $headers = ['视频标题', '视频内容', '视频话题', '口播文案', '口播情绪'];
                        if ($rowData !== $headers) {
                            return "解析失败:请按照模板格式上传";
                        }
                    } else {
                        // 校验数据行
                        if (mb_strlen($rowData[3]) > 400) {
                            return "解析失败:第{$rowCount}行文案字数超过400字";
                        }
                        $data[] = $rowData;
                    }
                }

                // 及时释放内存
                unset($cell, $cellIterator, $rowData);
            }

            // 校验数据量
            if (count($data) === 0) return "解析失败:没有有效数据";
            //if (count($data) > 100) return "解析失败:最多只能上传100条数据";

            return $data;
        } catch (Exception $e) {
            return "解析失败:" . $e->getMessage();
        } finally {
            // 显式释放资源
            if (isset($spreadsheet)) {
                $spreadsheet->disconnectWorksheets();
                unset($spreadsheet);
            }
            gc_collect_cycles();
        }
    }


    //短视频分享链接采集
    public function getShortVideoUrl($task)
    {
        $this->insetLog(1, $task['id'], "正在解析视频链接");
        $url = json_decode($task['share_urls'],true);
        $res = CozeService::instance()->runWorkflow("7502362477041106979",['input'=>$url]);
        return $res;
    }
    //查询coze运行结果(短视频分享链接采集)
    public function getShortVideoUrlResult($task,$execute_id,$task_run_log_id=0)
    {
        $this->insetLog(1, $task['id'], "正在查询解析视频链接结果");
        $res = CozeService::instance()->getWorkflowResult($execute_id,"7502362477041106979");
        //$this->app->log->info("查询coze运行结果".json_encode($res));
        if($res['code']==0){
            RedianTask::mQuery()->where(["id"=>$task['id']])->update(['progress'=>7,'error_msg'=>"采集失败"]);
            if($task_run_log_id){
                $this->app->db->name("task_run_log")->where(["id"=>$task_run_log_id])->update(['result'=>"采集失败"]);
            }
            return $res;
        }else{
            $data = $res['data'][0];
            if($data['execute_status']=="Success"){
                $output = json_decode($res['data'][0]['output'],true);

                $task_datas =  json_decode($output['Output'],true);
                //  $this->app->log->info("查询coze运行结果",$task_datas);
                $ys_num=0;
                if($task_datas['output']){
                    foreach ($task_datas['output'] as $k=>$t){
                        if($t['title']){

                            $save_data = [
                                'content'=>$t['video_data'],
                                'title'=>$t['title'],
                                'task_id'=>$task['id'],
                                'task_run_log_id'=>$task_run_log_id,
                                'push_time'=>"1970-01-01 00:00:00",
                                'filter_status'=>1,
                                'user_id'=>$task['user_id'],
                                'is_auto_fb'=>$task['is_auto_fb'],
                                'is_auto_jjjb'=>$task['is_auto_jjjb'],
                                'is_auto_fbjb'=> $task['is_auto_fbjb'],
                            ];
                            $this->insetLog(1,$task['id'],"解析到数据:{$t['title']}",$task_run_log_id);
                            $id = RedianData::mk()->insertGetId($save_data);
                            $save_data['id']=$id;
                            $r = MemberService::instance()->charge($task['user_id'],"UrlVideoToText",$save_data);
                            if($r['code']==0){
                                return $r;
                            }
                            $ys_num++;
                        }
                    }
                    $res['cdoe']=1;
                    return $res;
                }else{
                    $res['cdoe']=3;
                    return $res;
                }


            }else{
                $res['cdoe']=2;
                return $res;
            }
        }
    }


    //批量计算相似度
    public function batchSimilarity($task,$task_run_log_id=0)
    {
        $this->insetLog(1,$task['id'],"COSINE 文案匹配度计算中 ",$task_run_log_id);
        $user_id = $task['user_id'];
        $redian_data = RedianData::mQuery()->where(['task_id'=>$task['id'],'task_run_log_id'=>$task_run_log_id])->whereNull('similarity')
            ->select()->toArray();
        $model = "qwen-turbo-latest";
        $json_datas = [];
        $system = "# 角色
                您是基于语义深度理解的文本匹配引擎，专为关键字-语料库精准匹配场景设计。相似度计算满分为100,精确到小数点后两位。
                
                ### 核心架构
                1. 量子化语义编码
                - 融合SimCSE+Sentence-BERT双编码体系
                - 768维语义向量空间对齐
                - Word2vec-Glove混合词嵌入
                
                2. 动态特征工程
                ‖ 特征类型   ‖ 权重 ‖ 处理机制               ‖
                ‖------------‖-----‖----------------------‖
                ‖ 语义特征   ‖ 60% ‖ 对比学习+注意力聚焦   ‖
                ‖ 句法特征   ‖ 30% ‖ Bi-GRU特征选择器      ‖
                ‖ 统计特征   ‖ 10% ‖ TF-IDF自适应衰减      ‖
                
                3. 跨领域适配
                - 代码：AST结构比对（Levenshtein增强版）
                - 学术：LaTeX公式解析（支持120种数学符号）
                - 文学：平仄模式识别+意象向量建模
                - 商业：行业术语库动态加载（含23个领域）
                
                4. 智能清洗管道
                ‖ 处理阶段   ‖ 功能                      ‖
                ‖------------‖--------------------------‖
                ‖ 预处理     ‖ GPT-4净化+方言纠错        ‖
                ‖ 核心处理   ‖ 敏感词过滤(132种变体)     ‖
                ‖ 后处理     ‖ EMA平滑+3σ置信校准       ‖
                
                ## 性能标准
                1. 准确率：MSMARCO Top1 89.2% / TREC DL 83.5%
                2. 响应时延：238ms均值（P99<280ms）
                3. 数值容差：±0.03（99%置信区间）
                
                ## 异常处理
                ‖ 代码 ‖ 条件                  ‖ 处理方式          ‖
                ‖------‖----------------------‖------------------‖
                ‖ -1   ‖ 广告内容置信度>85%    ‖ 立即终止处理      ‖
                ‖ -2   ‖ 有效内容密度<15%      ‖ 返回空文本标识    ‖
                ‖ -3   ‖ 系统负载>95%          ‖ 触发熔断机制      ‖
                ===输出示例===
                85
                ===输出示例结束===
                
                ## 限制:
                1. 输出必须为[-2,-1,0.00-100.00]区间数字
                2. 严格禁止任何解释性文字
                3. 数值精度强制保留2位小数";
        $t = time();
        // 创建存储目录
        $jsonlDir = $this->app->getRootPath() . "public/jsonl/";
        if (!is_dir($jsonlDir)) {
            mkdir($jsonlDir, 0755, true);
        }

        $jsonl_file = "{$jsonlDir}similarity_{$task['id']}_{$task_run_log_id}_{$t}.jsonl";
        $requst_url = "/v1/chat/completions";
        foreach ($redian_data as $v){
            $text1 = $v['content'].$v['title'];
            $text2 = $task['keywords'];
            $user = " 请你计算以下两段文本的相似度：
                文本1：
                {$text1}
                 文本2：
                {$text2}";
            $json_data = [
                'custom_id'=>$v['id'],
                'method'=>"POST",
                'url'=>$requst_url,
                "body"=>[
                    'model'=>$model,
                    "messages"=>[
                        [
                            "role"=>"system",
                            "content"=>$system
                        ],
                        [
                            "role"=>"user",
                            "content"=>$user
                        ]
                    ]
                ]
            ];


            $json_datas[] = json_encode($json_data);
        }
        //将数据写入jsonl文件
        file_put_contents($jsonl_file, implode("\n", $json_datas),FILE_APPEND);
        $r = AlibailianService::instance()->uploadFile($user_id,$jsonl_file);
        if($r['code']==1){
            $p = AlibailianService::instance()->createBatch($user_id,$r['data'],$requst_url,$task['title']."-".$task_run_log_id."相似度计算");
            if($p['code']==1){
                //任务创建成功删除jsonl文件
                unlink($jsonl_file);
                return $p['data'];
            }else{
                return 0;
            }
        }else{
            return 0;
        }

    }

    //批量计算相似度结果查询
    public function batchSimilarityResult($user_id,$batch_id)
    {

        $res = AlibailianService::instance()->batchStatus($user_id,$batch_id);

        if($res['code']==0){
            $this->app->log->error('批量任务状态查询结果失败:'.json_encode($res));
            return 0;
        }
        $status = $res['data']['status'];
        if($status!="in_progress" && $status!="validating" && $status!="completed" ){
            $this->app->log->error('批量任务状态查询结果0:');
            return 0;
        }elseif($status=="in_progress" || $status=="validating"){
            $this->app->log->error('批量任务状态查询结果1:');
            return 1;
        }elseif($status=="completed"){
          //  $this->app->log->error('批量任务状态查询结果2:');
            //处理数据
            $d = AlibailianService::instance()->downloadBatch($user_id,$res['data']['output_file_id']);
           // $this->app->log->error('批量任务状态查询结果22:'.json_encode($d));
            if($d['code']==0){
                return 0;
            }
            $datas = explode("\n",$d['data']);
            foreach ($datas as $k=>$v){
                $data = json_decode($v,true);
                if(!empty($data)){
                    $custom_id = $data['custom_id'];
                    $similarity = $data['response']['body']['choices'][0]['message']['content'];
                    $redian_data = RedianData::mk()->where(['id'=>$custom_id])->find();
                    $this->insetLog(1,$redian_data['task_id'],"DTW 文案匹配度 {$similarity}",$redian_data['task_run_log_id']);
                    RedianData::mk()->where(['id'=>$custom_id])->update(['similarity'=>$similarity]);
                }

            }
          //  $this->app->log->error('批量任务状态查询结果22:');
            return 2;
        }else{
            $this->app->log->error('批量任务状态查询结果:'.json_encode($res));
            return 3;
        }

    }

    //取消批量任务
    public function cancelBatch($user_id,$batch_id){
        $res = AlibailianService::instance()->cancelBatch($user_id,$batch_id);
        if($res['code']==0){
            return 0;
        }else{
            return 1;
        }
    }


    //清除文本中乱七八糟的字符
    public function extractContent($text) {
        //$text = input('text');
        // 确保UTF-8编码处理
        if (!mb_check_encoding($text, 'UTF-8')) {
            $text = mb_convert_encoding($text, 'UTF-8', 'auto');
        }

        // 1. 移除所有导航项（包括中文和英文）
        $navItems = ['精选', '推荐', '关注', '朋友', '我的', '直播', '放映厅', '短剧',
            '下载', '广告投放', '用户服务协议', '隐私政策', '账号找回',
            '联系我们', '加入我们', '营业执照', '友情链接', '站点地图', '电商',
            '搜索', '充值', '客户端', '壁纸', '通知', '私信', '投稿',
            '登录', '综合', '视频', '用户', '多列', '单列', '筛选',
            '常见问题', '意见反馈', '首页', '发现', '消息', '个人中心',
            'Home', 'Discover', 'Message', 'Profile', 'Trending', 'Following'];

        // 创建导航项的正则模式（精确匹配）
        $navPattern = '/\b(' . implode('|', array_map(function($item) {
                return preg_quote($item, '/');
            }, $navItems)) . ')\b/u';

        $text = preg_replace($navPattern, '', $text);

        // 2. 移除日期和时间格式
        $text = preg_replace('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/u', '', $text); // 2022-06-16 00:00:00
        $text = preg_replace('/\d{4}年\d{1,2}月\d{1,2}日/u', '', $text);           // 2025年5月22日
        $text = preg_replace('/\d{1,2}月\d{1,2}日/u', '', $text);                  // 5月22日
        $text = preg_replace('/\d{1,2}:\d{2}/u', '', $text);                       // 00:09

        // 3. 移除所有版权和许可证信息
        $text = preg_replace('/\d{4} © .*/u', '', $text);
        $text = preg_replace('/京(公网安备|ICP).*/u', '', $text);
        $text = preg_replace('/(许可证|备案|证号|安备|文号|网文|证书|资质|备案号|注册号|执照|号-\d+).*/u', '', $text);

        // 4. 移除数字统计和来源标注
        $text = preg_replace('/[\d.,]+万?/', '', $text); // 12.4万, 1.8万
        $text = preg_replace('/@\s*[\w·]+(\s*·\s*[\d月日]+)?/u', '', $text); // @潮新闻 · 5月22日

        // 5. 移除特殊符号和标签
        $text = preg_replace('/#\S+/u', '', $text); // 移除话题标签
        $text = preg_replace('/\s*·\s*/u', ' ', $text); // 移除分隔点
        $text = preg_replace('/\s*&\s*/u', ' ', $text); // 移除&符号

        // 6. 移除重复的"word"序列和乱码
        $text = preg_replace('/\b(word\s*){3,}/iu', '', $text);
        $text = preg_replace('/mmMwWLliI0fiflO&\s*\d+/u', '', $text);

        // 7. 移除换行符和多余空格
        $text = preg_replace('/\R/u', ' ', $text); // 所有换行符替换为空格
        $text = preg_replace('/\s{2,}/u', ' ', $text); // 多个空格合并为一个

        // 8. 移除残留的短词和符号
        $text = preg_replace('/\b(\w{1,2}|\d+)\b/u', '', $text); // 移除1-2字母的单词和纯数字
        $text = preg_replace('/[^\p{L}\p{N}\s.,!?;:"\'()-]/u', '', $text); // 只保留字母、数字、标点和空格
        return trim($text);
    }

    //对标账号监控采集
    public function createAccountMonitor($task){
        $data = [
            'input'=>$task['home_page'],
        ];
        $res = CozeService::instance()->runWorkflow("7511634985201336357",$data);
        return $res;
    }
    //查询对标账号采集结果
    public function getAccountMonitorResult($task,$execute_id,$task_run_log_id=0,$workflow_id="7511634985201336357"){
        $res = CozeService::instance()->getWorkflowResult($execute_id,$workflow_id);
        if($res['code']==0){
            return 0;
        }else{
            $data = $res['data'][0];
            if($data['execute_status']=="Success"){
                $output = json_decode($res['data'][0]['output'],true);

                $task_datas =  json_decode($output['Output'],true);
                //$this->app->log->info("查询coze运行结果",$task_datas);
                $ys_num=0;
                if($task_datas['output']){
                    foreach ($task_datas['output'] as $k=>$t){
                        $share_url = $t['share_url'];
                        // 使用正则匹配 /video/ 后的数字部分
                        if (preg_match('/\/video\/(\d+)/', $share_url, $matches)) {
                            $videoId = $matches[1]; // 提取结果: "7512263637189365011"
                            $share_id  = $videoId;
                        } else {
                            $share_id = $share_url;
                        }
                        if(RedianData::mk()->where(['task_id'=>$task['id'],'task_run_log_id'=>$task_run_log_id])
                               ->where(['share_id'=>$share_id])->count()==0){
                            $save_data = [
                                'user_id'=>$task['user_id'],
                                'description'=>$t['desc'],
                                'content'=>$t['text'],
                                'time'=>$t['create_time'],
                                'share_url'=>$t['share_url'],
                                'share_id'=>$share_id,
                                'share_duration'=>$t['duration'],
                                'task_id'=>$task['id'],
                                'task_run_log_id'=>$task_run_log_id,
                                'filter_status'=>1,
                                'push_time'=>"1970-01-01 00:00:00"
                            ];
                            RedianData::mk()->insert($save_data);
                        }

                    }
                    return 1;
                }else{
                    return 3;
                }


            }else{
                return 2;
            }
        }
        return $res;
    }


    //小红书账号笔记采集
    //web/get_user_notes
    public function getXhsUserNotes($task,$task_run_log_id=0)
    {
        //用户id提取
        $home_page = $task['home_page'];
        if (preg_match('/\/user\/profile\/([a-f0-9]+)/i', $home_page, $matches)) {
            $user_id = $matches[1];
        } else {
            // 兜底方案：使用字符串截取
            $user_id = substr($home_page, strrpos($home_page, '/') + 1);
        }
        dump($user_id);
        $res = TikhubService::instance()->getXhsUserNotes($user_id);
        if($res['code']==0){
            return $res;
        }
        $data = $res['data'];
        dump($data);
        $save_datas =[];
        if(isset($data['data']['notes'])){
            $notes = $data['data']['notes'];
            dump($notes);
            foreach ($notes as $k=>$t){
                dump($t);
                $share_url = "";
                $video_duration = 0;
                if(isset($notes['video_info_v2']['media']['stream'])){
                    if(empty($share_url) && isset($video_info['h265']) && count($video_info['h265'])>0 && isset($video_info['h265'][0]['backup_urls']) && count($video_info['h265'][0]['backup_urls'])>0) {
                        $share_url = $video_info['h265'][0]['backup_urls'][0];
                        $video_duration = date("H:s",$video_info['h265'][0]['video_duration']/1000);
                    }
                    $video_info = $notes['video_info_v2']['media']['stream'];
                    if(isset($video_info['h264']) && count($video_info['h264'])>0 && isset($video_info['h264'][0]['backup_urls']) && count($video_info['h264'][0]['backup_urls'])>0) {
                        $share_url = $video_info['h264'][0]['backup_urls'][0];
                        $video_duration = date("H:s",$video_info['h264'][0]['video_duration']/1000);
                    }


                }
                $save_datas[]=$save_data = [
                    'user_id'=>$task['user_id'],
                    'description'=>$t['desc'],
                    'time'=>$t['create_time'],
                    'share_url'=>$share_url,
                    'share_id'=>$t['id'],
                    'share_duration'=>$video_duration,
                    'task_id'=>$task['id'],
                    'task_run_log_id'=>$task_run_log_id,
                    'filter_status'=>1,
                    'push_time'=>"1970-01-01 00:00:00"
                ];
                RedianData::mk()->insert($save_data);
            }
        }
        $res['data'] = $save_datas;
        return $res;
    }


    //小红书账号笔记采集
    //web/get_user_notes
    public function getXhsUserNotesApp($task,$task_run_log_id=0)
    {
        //用户id提取
        $home_page = $task['home_page'];
        if (preg_match('/\/user\/profile\/([a-f0-9]+)/i', $home_page, $matches)) {
            $user_id = $matches[1];
        } else {
            // 兜底方案：使用字符串截取
            $user_id = substr($home_page, strrpos($home_page, '/') + 1);
        }

        $res = TikhubService::instance()->getXhsUserNotes($user_id);
        dump($res);exit;
        if($res['code']==0){
            return $res;
        }
        $data = $res['data'];

        $save_datas =[];
        if(isset($data['data']['notes'])){
            $notes = $data['data']['notes'];
            foreach ($notes as $k=>$t){
                dump($t);
                $share_url = "";
                $video_duration = 0;
                if($t['type']=="video"){
                    if(RedianData::mQuery()->where(['user_id'=>$task['user_id'],'share_id'=>$t['note_id']])->count()==0){
                        //获取小红书笔记详情
                        $res = TikhubService::instance()->getXhsNoteInfoById($t['note_id']);
                    }
                }









                if(isset($notes['video_info_v2']['media']['stream'])){
                    if(empty($share_url) && isset($video_info['h265']) && count($video_info['h265'])>0 && isset($video_info['h265'][0]['backup_urls']) && count($video_info['h265'][0]['backup_urls'])>0) {
                        $share_url = $video_info['h265'][0]['backup_urls'][0];
                        $video_duration = date("H:s",$video_info['h265'][0]['video_duration']/1000);
                    }
                    $video_info = $notes['video_info_v2']['media']['stream'];
                    if(isset($video_info['h264']) && count($video_info['h264'])>0 && isset($video_info['h264'][0]['backup_urls']) && count($video_info['h264'][0]['backup_urls'])>0) {
                        $share_url = $video_info['h264'][0]['backup_urls'][0];
                        $video_duration = date("H:s",$video_info['h264'][0]['video_duration']/1000);
                    }


                }
                $save_datas[]=$save_data = [
                    'user_id'=>$task['user_id'],
                    'description'=>$t['desc'],
                    'time'=>$t['create_time'],
                    'share_url'=>$share_url,
                    'share_id'=>$t['id'],
                    'share_duration'=>$video_duration,
                    'task_id'=>$task['id'],
                    'task_run_log_id'=>$task_run_log_id,
                    'filter_status'=>1,
                    'push_time'=>"1970-01-01 00:00:00"
                ];
                RedianData::mk()->insert($save_data);
            }
        }
        $res['data'] = $save_datas;
        return $res;
    }


    //抖音账号视频采集
    public function getDyUserNotes($task,$task_run_log_id=0){
        $this->insetLog(1,$task['id'],"正在采集对标账号视频数据",$task_run_log_id);
        $home_page = $task['home_page'];
        if (preg_match('/\/user\/([A-Fa-f0-9]+)[\W_]*/i', $home_page, $matches)) {
            $user_id = $matches[1];
        } else {
            // 处理带参数的URL
            $path = explode('?', $home_page)[0];
            $segments = explode('/', $path);
            $user_id = end($segments);
        }
        if(empty($user_id)){
            return ['code'=>-1,'msg'=>'抖音账号ID获取失败,请检查主页URL是否正确'];
        }

        try {
            $res = TikhubService::instance()->getDyUserVideos($user_id);
            if($res['code']==0){
                return $res;
            }
            $r = MemberService::instance()->charge($task['user_id'],"AccountGatherDy",$task);
            if($r['code']==0){
                return $r;
            }
           // $this->app->log->error("抖音账号视频采集失败".json_encode($res));
            $data = $res['data'];
            $save_datas =[];
            foreach ($data['aweme_list'] as $t){
                $is_repeat = RedianData::mQuery()->where(['task_id'=>$task['id'],'share_id'=>$t['aweme_id']])->count();
                if($is_repeat==0 && $t['create_time']>(strtotime($task['create_at'])-60)){
                    $save_datas[]=$save_data = [
                        'user_id'=>$task['user_id'],
                        'description'=>$t['desc'],
                        'time'=>$t['create_time'],
                        'share_url'=>$t['share_url'],
                        'share_id'=>$t['aweme_id'],
                        'share_duration'=>date("i:s",ceil($t['duration']/1000)),
                        'task_id'=>$task['id'],
                        'task_run_log_id'=>$task_run_log_id,
                        'is_repeat'=>$is_repeat>0?1:0,
                        'push_time'=>"1970-01-01 00:00:00",
                        'is_auto_fb'=>$task['is_auto_fb'],
                        'is_auto_jjjb'=>$task['is_auto_jjjb'],
                        'is_auto_fbjb'=> $task['is_auto_fbjb'],
                    ];
                    $this->insetLog(1,$task['id'],"采集到视频数据:{$t['desc']}",$task_run_log_id);
                    RedianData::mk()->insert($save_data);
                }


            }
            $res['data'] = $save_datas;
            return $res;
        }catch (\Exception $e){
            return ['code'=>0,'msg'=>$e->getMessage()];
        }




    }

    //创建提取视频中的音频文字任务
    public function createVideoAudioText($task,$task_run_log_id=0){
        $data = RedianData::mQuery()
            ->where(['task_id'=>$task['id'],'task_run_log_id'=>$task_run_log_id,'is_repeat'=>0])
            ->whereNull("content")->order("time desc")->find();
        if(empty($data)){
            return ['code'=>-1,'msg'=>'已执行采集，暂未发现新作品！'];
        }
        $this->insetLog(1,$task['id'],"正在提取视频中的音频文字",$task_run_log_id);
        $p = [
            "share_url"=>$data['share_url'],
            "data_id"=>$data['id']
        ];
        $res = CozeService::instance()->runWorkflow("7514004990677532709",$p);
        return $res;
    }

    //查询提取视频中的音频文字任务结果
    public function getVideoAudioTextResult($task,$execute_id,$task_run_log_id=0){

        $res = CozeService::instance()->getWorkflowResult($execute_id,"7514004990677532709");
        if($res['code']==0){
            return $res;
        }

       // $this->app->log->error("getVideoAudioTextResult".json_encode($res));
        $data = $res['data'][0];
        if($data['execute_status']=="Success"){
            $output = json_decode($res['data'][0]['output'],true);
            $task_datas =  json_decode($output['Output'],true);
            if($task_datas){
                //$output = $task_datas['output'];
                $r_data= RedianData::mQuery()->where(['id'=>$task_datas['data_id']])->find();
                $r = MemberService::instance()->charge($task['user_id'],"VideoToText",$r_data);
                if($r['code']==0){
                    return $r;
                }
                $this->insetLog(1,$task['id'],"已提取视频中的音频文字",$task_run_log_id);
                RedianData::mQuery()->where(['id'=>$task_datas['data_id']])->update(['content'=>$task_datas['content'],'filter_status'=>1]);
                return $res;
            }else{
                $res['code']=3;
                return $res;
            }
        }else{
            $res['code']=2;
            return $res;
        }
    }
}
